import { Translate } from '@renderer/service'
import { post, getStoreConfig } from "@renderer/utils";

enum Locale {
	'auto' = 'auto',
    'zh-CN' = 'zh',
    'en-US' = 'en',
    'zh-TW' = 'cht'
}

interface TransResult {
	src: string,
	dst: string
}

interface BaiduResponse {
	from: string,
	to: string,
	trans_result: Array<TransResult>,
	error_code?: number,
	error_msg?: string,
	src_tts?: string,
	dst_tts?: string,
	dict?: string,
	[key:string]: any
}



export default class BaiduTranslate implements Translate{
	public readonly name = "百度翻译"
	public readonly id = crypto.randomUUID()
	public readonly delay = 100
	private appid = ''
	private secret = ''

	constructor(){
		getStoreConfig().then(config => {
			const { baidu } = config
			this.setAuthorization(baidu)
		})
	}

	public translate(keywords: string, to: string, from: string='auto'){
		const requestParams = this.createParams(keywords, to, from)
		return new Promise<TranslateResponse>((resolve,reject) => {
			post<BaiduResponse>('https://fanyi-api.baidu.com/api/trans/vip/translate', requestParams, {
				headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
			}).then(res => {
				if(res.error_code) return reject(new Error(res.error_msg))
				resolve({ status: 'success', from, to, keywords, data: res.trans_result[0].dst })
			}).catch(e => {
				if(e instanceof PromiseRejectionEvent) reject(new Error(e.reason))
				if(e instanceof Error) reject(new Error(e.message))
			})
		})
	}
	
	createParams(keywords: string, to: string, from: string ='auto'){
		const salt = Math.ceil(Math.random() * new Date().getTime())
		const sign = window.bridge.md5(this.appid + keywords + salt + this.secret)
		return { q: keywords, from:Locale[from], to: Locale[to], appid: this.appid, salt, sign }
	}

	setAuthorization(authorization:BaiduAuthorization){
		this.appid = authorization.appid
		this.secret = authorization.secret
	}
}
